package com.example.lanouhn.firstapp.activity.fragment;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.activity.BrokerDealerActivity;
import com.example.lanouhn.firstapp.activity.activity.GoodsDetailsActivity;
import com.example.lanouhn.firstapp.activity.activity.GoodsListActivity;
import com.example.lanouhn.firstapp.activity.activity.HelpActivity;
import com.example.lanouhn.firstapp.activity.activity.MainActivity;
import com.example.lanouhn.firstapp.activity.activity.SearchGoodsListActivity;
import com.example.lanouhn.firstapp.activity.adapter.HomePageAdapter;
import com.example.lanouhn.firstapp.activity.adapter.HomePageOneAdapter;
import com.example.lanouhn.firstapp.activity.constants.Constants;
import com.example.lanouhn.firstapp.activity.model.Carousel;
import com.example.lanouhn.firstapp.activity.model.HomePage;
import com.example.lanouhn.firstapp.activity.model.HomePageOne;
import com.example.lanouhn.firstapp.activity.utils.CarouselJson;
import com.example.lanouhn.firstapp.activity.utils.HomePageJson;
import com.example.lanouhn.firstapp.activity.utils.HomePageLimitedgoosJson;
import com.example.lanouhn.firstapp.activity.utils.HttpUtils;
import com.example.lanouhn.firstapp.activity.view.ad.SlideShowViewOne;

import java.util.List;

//首页界面的最新商品列表、限时商品列表

public class HomePageFragment extends Fragment {
    //定义RecyclerView 最新商品
    private RecyclerView recyclerView;
    //数据集合
    private List<HomePage> list;
    //适配器
    private HomePageAdapter adapter;
    //定义 ProgressBar
    private ProgressBar progressBar;
    private ProgressBar oneProgressBar;
    //轮播图 数据集合
    private List<Carousel> iList;
    private SlideShowViewOne slideShowViewOne;
    //限时商品
    private RecyclerView recyclerview;
    private List<HomePageOne> hList;
    private HomePageOneAdapter hAdapter;

    //首页商品分类
    private ImageView homepage_goods;
    //首页购物车
    private ImageView homepage_shoppingCart;
    //首页界面的自营按钮
    private ImageView homepage_brokerDealer;
    //个人中心按钮
    private ImageView homepage_personCenter;
    //首页帮助按钮
    private ImageView homepage_help;
    //首页搜索按钮
    private ImageView homepage_search;
    private EditText homepage_editText;
    //线程
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //取消loading
            progressBar.setVisibility(View.GONE);
            oneProgressBar.setVisibility(View.GONE);
            switch (msg.what) {

                case 0:
                    showDialog3(getActivity(), "网络链接失败....", false);

                    break;
                case 1:
                    //创建adapter 最新商品列表适配器
                    adapter = new HomePageAdapter(list, getActivity());
                    //绑定adapter
                    recyclerView.setAdapter(adapter);
                    //执行完毕，更新UI,
                    adapter.notifyDataSetChanged();


                    //recyclerView的监听事件
                    adapter.setRecyclerViewListener(new HomePageAdapter.RecyclerViewListener() {
                        @Override
                        public void onClick(View view, int position) {
                            Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                            //携带id进行传值跳转到商品详情页面
                            intent.putExtra("goods_id", list.get(position).getGoods_id());
                            startActivity(intent);

                        }
                    });


                    //创建adapter 限时商品列表适配器
                    hAdapter = new HomePageOneAdapter(hList, getActivity());
                    recyclerview.setAdapter(hAdapter);

                    hAdapter.setOneRecyclerViewListener(new HomePageOneAdapter.OneRecyclerViewListener() {
                        @Override
                        public void onClick(View view, int position) {
                            Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                            //携带id进行传值跳转到商品详情页面
                            intent.putExtra("goods_id", list.get(position).getGoods_id());
                            startActivity(intent);
                        }
                    });

                    //轮播图
                    slideShowViewOne.initData(iList);
                    break;


            }


        }
    };



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.homepagefragment, null);


        //找到控件
        initView(view);
        //监听事件
        initEvent(view);
        //请求网络数据
        getDataFromWeb();
        return view;

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    private void getDataFromWeb() {
        //设置加载进度是可见的
        progressBar.setVisibility(View.VISIBLE);
        oneProgressBar.setVisibility(View.VISIBLE);
        //请求网络数据 开启线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用HttpUtils类，来请求网络获取Json数据
                String result = HttpUtils.doGet(Constants.HOMEPAGE_LIST_URL);

                //是否获取到Json数据
                if (!result.equals("") && !result.equals("null")) {

                    //将获取到的json数据解析，通过封装的工具类
                    list = HomePageJson.getHomePage(result);

                    hList = HomePageLimitedgoosJson.getHomePageOne(result);

                    iList = CarouselJson.getCarousel(result);

                    //判断解析出的集合的长度，有数据就显示，无数据就不显示
                    if (list.size() > 0 || hList.size() > 0 || iList.size() > 0) {

                        //获取数据成功
                        handler.sendEmptyMessage(1);
                    } else {
                        //失败
                        handler.sendEmptyMessage(0);
                    }

                } else {
                    //获取Json数据失败
                    handler.sendEmptyMessage(0);

                }


            }
        }).start();


    }

    private void initEvent(View view) {


        homepage_goods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(
                        getActivity(), MainActivity.class);
                intent.putExtra("symbol",2);
                startActivity(intent);
            }
        });
        //自营按钮监听事件
        homepage_brokerDealer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(
                        getActivity(), BrokerDealerActivity.class);
                startActivity(intent);
                //getActivity().startActivityForResult(intent,111);
                getActivity().overridePendingTransition(R.anim.translatein,R.anim.translateout);
            }
        });

        homepage_shoppingCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(
                        getActivity(), MainActivity.class);
                intent.putExtra("symbol",3);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.translatein,R.anim.translateout);
            }
        });
        //个人中心按钮监听事件
        homepage_personCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(
                       getActivity(),MainActivity.class);
                intent.putExtra("symbol",4);
                 startActivity(intent);
                getActivity().overridePendingTransition(R.anim.translatein,R.anim.translateout);
            }
        });
        //搜索监听事件
        homepage_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), GoodsListActivity.class);
                startActivityForResult(intent,100);
                getActivity().overridePendingTransition(R.anim.translatein,R.anim.translateout);
            }
        });
        //搜索框监听事件
        homepage_editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(
                        getActivity(), SearchGoodsListActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.translatein,R.anim.translateout);
            }
        });

        homepage_help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(
                        getActivity(), HelpActivity.class);
                getActivity().startActivityForResult(intent,122);
                getActivity().overridePendingTransition(R.anim.translatein,R.anim.translateout);
            }
        });


    }


    //绑定控件
    private void initView(View view) {

        //轮播图
        slideShowViewOne = (SlideShowViewOne) view.findViewById(R.id.slideShowViewOne);

        homepage_goods = (ImageView) view.findViewById(R.id.homepage_goods);
        homepage_shoppingCart = (ImageView) view.findViewById(R.id.homepage_shoppingCart);
        homepage_personCenter = (ImageView) view.findViewById(R.id.homepage_personCenter);
        homepage_brokerDealer = (ImageView) view.findViewById(R.id.homepage_brokerDealer);
        homepage_help = (ImageView) view.findViewById(R.id.homepage_help);

        homepage_search = (ImageView) view.findViewById(R.id.homepage_search);
        homepage_editText = (EditText) view.findViewById(R.id.homepage_editText);


        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        oneProgressBar = (ProgressBar) view.findViewById(R.id.oneProgressBar);
        //绑定RecyclerView控件 首页的最新商品列表
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

        //加载布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        //设置图片距离 首页的最新商品列表
        SpacesItemDecoration decoration = new SpacesItemDecoration(9);
        recyclerView.addItemDecoration(decoration);

        //绑定RecyclerView控件 首页的限时商品列表
        recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(getActivity(), 2);
        recyclerview.setLayoutManager(gridLayoutManager1);

        SpacesItemDecoration decoration1 = new SpacesItemDecoration(7);
        recyclerview.addItemDecoration(decoration1);

    }

    //设置图片距离
    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpacesItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.top = space;
            }
        }
    }

    public void showDialog3(final Context context, String msg, boolean goHome) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(msg).setCancelable(false);

        //设置图标
        builder.setIcon(R.mipmap.ic_launcher);
        //设置标题
        builder.setTitle("提示");
        builder.setPositiveButton("请点击这里重新加载", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                getDataFromWeb();
            }
        });

        //创建并显示
        builder.create().show();
    }

}
